#!/bin/sh
# PCP QA Test No. 1296
# pmie disconnect+reconnect rule scheduler bug
#
# Copyright (c) 2021 Ken McDonell.  All Rights Reserved.
#

if [ $# -eq 0 ]
then
    seq=`basename $0`
    echo "QA output created by $seq"
else
    # use $seq from caller, unless not set
    [ -n "$seq" ] || seq=`basename $0`
    echo "QA output created by `basename $0` $*"
fi

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

_cleanup()
{
    cd $here
    $sudo rm -rf $tmp $tmp.*
}

status=0	# success is the default!
trap "_cleanup; exit \$status" 0 1 2 3 15

_filter()
{
    sed \
	-e '/^Log for pmie on /s/ on .*/ on .../' \
	-e '/^pmie: PID =/s/ = .*/ = .../' \
	-e '/^Log finished /s/ finished .*/ finished .../' \
	-e 's/.* pmie([0-9][0-9]*) //' \
	-e 's/pmFetch from [^ ][^ ]* failed:/pmFetch from ... failed:/' \
    | $PCP_AWK_PROG '
/I am alive/	{ alive++
		  if (alive == 3) print "I am alive (at least 3 times)"
		  next
		}
/Re-established connection/	{ alive = 0 }
		{ print }'
}

cat <<'End-of-File' >$tmp.config
delta = 1;
hinv.ncpu > 0 -> print "I am alive";
End-of-File

# real QA test starts here
export PMCD_RECONNECT_TIMEOUT=1
pmie -c $tmp.config -l $tmp.log -U `id -un` >$tmp.out 2>&1 &
pid=$!
sleep 5
if ! _service pmcd stop >>$seq_full 2>&1; then _exit 1; fi
sleep 5
if ! _service pmcd restart >>$seq_full 2>&1; then _exit 1; fi
sleep 5
kill -TERM $pid
wait
echo "=== pmie output ==="
cat $tmp.out
echo
echo "=== pmie.log ==="
# Especially on slow VMs (like bozo-vm) we may need to dodge warnings
# from pmie's rule scheduler around pmcd reconnection ... the final
# awk script does this.
#
tee -a $seq_full < $tmp.log \
| _filter \
| $PCP_AWK_PROG '
skip == 1 && /^[^ ]/		{ skip = 0 }
/^run: schedule eval/		{ skip = 1 }
/^sleepTight: negative/		{ skip = 1 }
/^Last sleepTight until:/	{ skip = 1 }
/^This sleepTight\() entry:/	{ skip = 1 }
/^Harvest children done:/	{ skip = 1 }
/^Want sleepTight until:/	{ skip = 1 }
/Task dump @/			{ skip = 1 }
skip == 0			{ print }'

# success, all done
exit
